'''
-*- coding: utf-8 -*-
@File  : qq_shanmh.py
@Author: Shanmh
@Time  : 2024/01/30 上午11:56
@Function：
'''
import queue
import time

from channel.channel import Channel
from aiocqhttp import CQHttp, Event
from common import log
from concurrent.futures import ThreadPoolExecutor
import multiprocessing
from model.poe.mypoe import  MyPoe
import threading
# thread_pool = ThreadPoolExecutor(max_workers=8)
print("第 n 次加载这个文件了")

bot = CQHttp(api_root='http://127.0.0.1:5700')
print("开始启动 bot  8080 ")
pull_q=queue.Queue(30)
poe=MyPoe()
if not hasattr(poe, 'br'):
    poe.init()
    poe.start_poe()
#
#
#
# pull_q = multiprocessing.Queue(30)
def _pull_img(pull_q):
    global bot

    print("询问队列开始执行")

    global poe
    count=0

    while True:
        if pull_q.qsize()>0:
            print("开始询问")
            user_id,message,type,group_id=pull_q.get()[:4]
            poe.send(message)
            time.sleep(1)
            reply_text=poe.receive()
            try:
                if type=="group":
                    print(group_id,user_id)
                    reply_text = '[CQ:at,qq=' + str(user_id) + '] ' + reply_text
                    bot.sync.send_group_msg(group_id=group_id, message=reply_text)
                    pass
                else:
                    bot.sync.send_private_msg(user_id=user_id, message=reply_text)

                    pass
            except:
                print("发送消息失败！！！！！！！！！！！")
        else:
            count+=1
            if count%50==0:
                print(f"当前队列{pull_q.qsize()}")
            time.sleep(0.2)


# def runbot(bot):
#     bot.run(host='127.0.0.1', port=8080)
#

t = threading.Thread(target=_pull_img, args=(pull_q,))
t.start()
# p_pull_img = multiprocessing.Process(target=_pull_img, args=(pull_q,))
# p_bot = multiprocessing.Process(target=runbot, args=(bot,))
# p_bot.start()
# p_pull_img.start()
# p_pull_img.join()
@bot.on_message('private')
def handle_private_msg(event: Event):
    log.info("event: {}", event)
    QQChannel().handle(event)

@bot.on_message('group')
def handle_private_msg(event: Event):
    log.info("event: {}", event)
    QQChannel().handle_group(event)


    # if not hasattr(poe, 'br'):
    #     poe.init()
    #     poe.start_poe()

class QQChannel(Channel):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance
    def startup(self):
        bot.run(host='127.0.0.1', port=8080)

        pass

    def create_q(self):
        self.poe_q=queue.Queue(30)


    # private chat
    def handle(self, msg):
        self._do_handle(msg)
        #thread_pool.submit(self._do_handle, msg)

    def _do_handle(self, msg):
        global pull_q
        print("发送到队列里")
        context = dict()
        log.info("event: {}", "do_handle")
        context['from_user_id'] = msg.user_id
        if pull_q.qsize()>5:
            reply_text = "当前用户过多请稍候询问"#super().build_reply_content(msg.message, context)
            bot.sync.send_private_msg(user_id=msg.user_id, message=reply_text)
        else:
            print(pull_q.qsize())
            pull_q.put([msg.user_id,msg.message,"user",""])
            print(pull_q.qsize())

    # group chat
    def handle_group(self, msg):
        self._do_handle_group(msg)
        #thread_pool.submit(self._do_handle_group, msg)

    def _do_handle_group(self, msg):
        context = dict()
        if msg.message and msg.message.find('CQ:at'):
            receiver = msg.message.split('qq=')[1].split(']')[0]
            if receiver == str(msg['self_id']):
                text_list = msg.message.split(']', 2)
                if len(text_list) == 2 and len(text_list[1]) > 0:
                    query = text_list[1].strip()
                    context['from_user_id'] = str(msg.user_id)
                    if pull_q.qsize() > 5:
                        reply_text = "当前用户过多请稍候询问"  # super().build_reply_content(msg.message, context)
                        reply_text = '[CQ:at,qq=' + str(msg.user_id) + '] ' + reply_text
                        bot.sync.send_group_msg(group_id=msg['group_id'], message=reply_text)
                    else:
                        pull_q.put([msg.user_id,query, "group",msg['group_id']])


                    reply_text = super().build_reply_content(query, context)
                    reply_text = '[CQ:at,qq=' + str(msg.user_id) + '] ' + reply_text

                    #bot.sync.send_group_msg(group_id=msg['group_id'], message=reply_text)